from django.http import JsonResponse
from django.views.decorators.http import require_http_methods
from django.views.decorators.csrf import csrf_exempt
import json
from web.models import ParticipationRecord, User, Activity, Reward
from django.utils import timezone
from django.forms.models import model_to_dict
from django.db.models import Count
from datetime import datetime, timedelta

@csrf_exempt
@require_http_methods(["POST"])
def participate(request):
    """参与活动"""
    try:
        data = request.POST
        user_id = data.get('user_id')
        activity_id = data.get('activity_id')
        
        try:
            user = User.objects.get(user_id=user_id)
            activity = Activity.objects.get(id=activity_id)
        except (User.DoesNotExist, Activity.DoesNotExist):
            return JsonResponse({'code': 404, 'message': '用户或活动不存在'})
            
        # 检查是否已参与
        if ParticipationRecord.objects.filter(user=user, activity=activity).exists():
            return JsonResponse({'code': 400, 'message': '已经参与过该活动'})
            
        # 创建参与记录
        participation = ParticipationRecord.objects.create(
            user=user,
            activity=activity,
            status=5
        )
        
        return JsonResponse({
            'code': 200,
            'message': '参与成功',
            'data': {
                'participation_id': participation.id
            }
        })
    except Exception as e:
        return JsonResponse({'code': 500, 'message': str(e)})

@csrf_exempt
@require_http_methods(["POST"])
def complete_activity(request):
    """完成活动"""
    try:
        data = request.POST
        user_id = data.get('user_id')
        activity_id = data.get('activity_id')
        # 是否完成
        is_complete = data.get('is_complete') 

        # 获取奖励
        reward_id = data.get('reward_id')
        # 如果 reward_id 是null
        if reward_id == "null":
            reward_id = None

        # 检查是否已参与
        if not ParticipationRecord.objects.filter(user__user_id=user_id, activity_id=activity_id).exists():
            return JsonResponse({'code': 400, 'message': '未参与该活动'})

        # 如果 completion_time 不为空，则表示已经提交过
        if ParticipationRecord.objects.filter(user__user_id=user_id, activity_id=activity_id, completion_time__isnull=False).exists():
            return JsonResponse({'code': 400, 'message': '您已经结束了本次活动'})

      
        reward_obj = Reward.objects.filter(id=reward_id, activity_id=activity_id).first()

        if is_complete == 'true':
            # 如果 reward_id 为空，则表示没有奖励
            if not reward_id:
                return JsonResponse({'code': 400, 'message': '你需要提供奖励'})
            # 判断奖励是否存在于活动
            if not reward_obj:
                return JsonResponse({'code': 400, 'message': '奖励不存在'})
            is_complete = True
            
        else:
            is_complete = False
            reward_id = None


        try:
           
            participation = ParticipationRecord.objects.get(
                user__user_id=user_id,
                activity_id=activity_id,
                completion_status=False,
            )
        except ParticipationRecord.DoesNotExist:
            # 如果执行到这里，是什么原因?
            # 1. 用户未参与活动
            # 2. 用户已经提交过
            # 3. 奖励不存在
            return JsonResponse({'code': 404, 'message': '未找到有效的参与记录'})
            
        # 更新完成状态
        participation.completion_status = is_complete
        participation.completion_time = timezone.now()
        participation.reward_id = reward_id
        participation.save()

        if is_complete:
            # 更新审核进度, 改为1
            participation.status = 1
            participation.save()
            
            # 商品减少
            reward_obj.remaining -= 1
            reward_obj.save()
        else:
            # 更新审核进度, 改为2
            participation.status = 2
            participation.remark = "用户自主结束"
            participation.save()
        
         
        return JsonResponse({
            'code': 200,
            'message': '活动完成',
            'data': {
                'completion_time': participation.completion_time
            }
        })
    except Exception as e:
        return JsonResponse({'code': 500, 'message': str(e)}) 


# 获取参与记录列表
@require_http_methods(["GET"])
def participation_list(request):
    """获取所有参与记录"""
    try:
        user_id = request.GET.get('user_id')
        participations = ParticipationRecord.objects.filter(user__user_id=user_id)
        participation_list = []
        # 获取参与记录, 包含活动信息和奖励信息
        for participation in participations:
            activity = Activity.objects.filter(id=participation.activity_id).first()
            # 转换活动信息
            activity_dict = model_to_dict(activity)
            activity_dict['cover_image'] = activity.cover_image.url
            activity_dict['created_at'] = activity.created_at.strftime("%Y-%m-%d %H:%M:%S")
            activity_dict['updated_at'] = activity.updated_at.strftime("%Y-%m-%d %H:%M:%S")

            if activity:
                # 判断我是否结束了这场活动
                if participation.completion_time:
                    activity_dict['status'] = 'this_activity_is_over'
            
               
                participation_list.append({
                    'id': participation.id,
                    'activity': activity_dict,
                })
        return JsonResponse({'code': 200, 'message': '获取成功', 'data': participation_list})
    except Exception as e:
        return JsonResponse({'code': 500, 'message': str(e)})
    


# 判断是否参与并且已经结束了活动
@require_http_methods(["GET"])
def is_participated_and_ended(request):
    """判断是否参与并且已经结束了活动"""
    try:
        user_id = request.GET.get('user_id')
        activity_id = request.GET.get('activity_id')
        # 判断 completion_time 是否为空
        if ParticipationRecord.objects.filter(user__user_id=user_id, activity_id=activity_id, completion_time__isnull=False).exists():
            # 已经结束了活动
            return JsonResponse({'code': 200, 'message': '获取成功', 'data': True})
        else:
            # 未结束
            return JsonResponse({'code': 200, 'message': '获取成功', 'data': False})
    except Exception as e:
        return JsonResponse({'code': 500, 'message': str(e)})



@csrf_exempt
# 审批活动
@require_http_methods(["POST"])
def approve_activity(request):
    """审批活动"""
    try:
        # 获取活动id
        activity_id = request.POST.get('activity_id')
        activity = Activity.objects.filter(id=activity_id).first()
        if not activity:
            return JsonResponse({'code': 404, 'message': '活动不存在'})
        
        participation_id = request.POST.get('participation_id')
        participation = ParticipationRecord.objects.filter(id=participation_id).first()
        if not participation:
            return JsonResponse({'code': 404, 'message': '参与记录不存在'})
        user_id = request.POST.get('user_id')
        if not user_id:
            return JsonResponse({'code': 404, 'message': '用户id不存在'})
        user = User.objects.filter(user_id=user_id).first()
        if not user:
            return JsonResponse({'code': 404, 'message': '用户不存在'})
        
        # 判断用户是不是本次参与活动的用户
        if participation.user_id != user_id:
            return JsonResponse({'code': 404, 'message': '用户不是本次参与活动的用户'})
        
        # 获取审批状态
        status = request.POST.get('status')
        # 判断审批状态是不是数字，如果不是尝试转换，如果转换失败直接返回
        try:
            status = int(status)
        except ValueError:
            return JsonResponse({'code': 400, 'message': '审批状态错误'})
        # 判断审批状态是否正确,只能是1 、2
        if status not in [2,3]:
            return JsonResponse({'code': 400, 'message': '审批状态错误'})
        
        # 留言
        remark = request.POST.get('remark')
        # 保证留言不为空或者没有
        if not remark or remark == '':
            return JsonResponse({'code': 400, 'message': '留言不能为空'})

        # 更新审批状态
        participation.status = status
        participation.remark = remark
        participation.save()

        # 获取奖励
        reward_obj = Reward.objects.filter(id=participation.reward_id).first()

        # 如果 status == 2 ，则表示不通过，则需要将奖励数量增加
        if status == 2:
            reward_obj.remaining += 1
            reward_obj.save()

        return JsonResponse({'code': 200, 'message': '活动审批成功'})
    except Exception as e:
        return JsonResponse({'code': 500, 'message': str(e)})

@csrf_exempt
@require_http_methods(["GET"])
def participation_statistics(request):
    try:
        # 获取查询参数
        days = int(request.GET.get('days', 7))  # 默认7天
        status = request.GET.get('status', '')  # 活动状态筛选
        
        # 计算时间范围
        end_date = timezone.now()
        start_date = end_date - timezone.timedelta(days=days)
        
        # 构建基础查询
        base_query = ParticipationRecord.objects.filter(
            created_at__range=(start_date, end_date)
        )
        
        if status:
            base_query = base_query.filter(activity__status=status)

        # 1. 基础统计数据
        total_participants = base_query.values('user').distinct().count()
        total_activities = base_query.values('activity').distinct().count()
        
        # 统计各状态数量
        status_counts = {
            'pending': base_query.filter(status=1).count(),  # 未审核
            'rejected': base_query.filter(status=2).count(), # 不通过
            'approved': base_query.filter(status=3).count(), # 通过
            'default': base_query.filter(status=4).count(),  # 默认状态
            'ongoing': base_query.filter(status=5).count()   # 正在参与中
        }
        
        # 计算总数
        total_count = sum(status_counts.values())
        
        # 计算比率
        avg_participation_rate = round((total_participants / Activity.objects.count()) * 100, 2) if Activity.objects.exists() else 0
        
        # 完成率 = 通过数 / (总数 - 未审核数 - 正在参与中数)
        valid_total = total_count - status_counts['pending'] - status_counts['ongoing']
        completion_rate = round((status_counts['approved'] / valid_total * 100), 2) if valid_total > 0 else 0

        # 2. 活动参与趋势数据
        trend_data = []
        for i in range(days):
            current_date = start_date + timedelta(days=i)
            next_date = current_date + timedelta(days=1)
            count = base_query.filter(
                created_at__gte=current_date,
                created_at__lt=next_date
            ).count()
            trend_data.append({
                'date': current_date.strftime('%Y-%m-%d'),
                'count': count
            })

        # 3. 热门活动排行
        top_activities = (
            base_query
            .values('activity__title')
            .annotate(count=Count('id'))
            .order_by('-count')[:5]
        )

        # 4. 状态分布
        status_distribution = (
            base_query
            .values('status')
            .annotate(count=Count('id'))
            .order_by('status')
        )

        # 5. 时段分布
        hourly_distribution = []
        for hour in range(24):
            count = base_query.filter(
                created_at__hour=hour
            ).count()
            hourly_distribution.append({
                'hour': hour,
                'count': count
            })

        # 构建返回数据
        response_data = {
            'total_participants': total_participants,
            'total_activities': total_activities,
            'avg_participation_rate': avg_participation_rate,
            'completion_rate': completion_rate,
            'status_counts': status_counts,
            'trend_data': trend_data,
            'top_activities': [
                {
                    'title': item['activity__title'],
                    'count': item['count']
                } for item in top_activities
            ],
            'status_distribution': [
                {
                    'status': get_status_text(item['status']),
                    'count': item['count']
                } for item in status_distribution
            ],
            'hourly_distribution': hourly_distribution
        }

        return JsonResponse({
            'code': 200,
            'message': '获取统计数据成功',
            'data': response_data
        })

    except Exception as e:
        return JsonResponse({
            'code': 500,
            'message': f'获取统计数据失败: {str(e)}'
        })

def get_status_text(status):
    status_map = {
        1: '未审核',
        2: '不通过',
        3: '通过',
        4: '默认状态',
        5: '正在参与中'
    }
    return status_map.get(status, '未知状态')

@csrf_exempt
@require_http_methods(["GET"])
def get_approval_list(request):
    """获取待审批列表"""
    try:
        # 获取状态筛选参数
        status = request.GET.get('status', '')
        print(status)
        
        # 构建基础查询
        query = ParticipationRecord.objects.all().select_related('user', 'activity', 'reward')
        
        # 如果有状态筛选
        if status:
            query = query.filter(status=status)
            
        # 获取记录列表
        records = query.order_by('-created_at')
        
        # 构建返回数据
        data = [{
            'id': record.id,
            'user': {
                'user_id': record.user.user_id,
                'username': record.user.username
            },
            'activity': {
                'id': record.activity.id,
                'title': record.activity.title
            },
            'reward': {
                'id': record.reward.id if record.reward else None,
                'image': record.reward.image.url if record.reward and record.reward.image else None
            } if record.reward else None,
            'status': record.status,
            'remark': record.remark,
            'created_at': record.created_at,
            'completion_time': record.completion_time
        } for record in records]
        
        return JsonResponse({
            'code': 200,
            'message': '获取审批列表成功',
            'data': data
        })
    except Exception as e:
        return JsonResponse({
            'code': 500,
            'message': f'获取审批列表失败: {str(e)}'
        })



